package task

import (
	"encoding/base64"
	"encoding/json"
	"github.com/gogf/guuid"
	"go.uber.org/zap"
	"regexp"
	"strings"
	"sync/atomic"
	"time"
)

// server
type WasTokenBean struct {
	Dt                  string `json:"dt"`
	Country             string `json:"country"` //1
	ClientId            string `json:"gid"`
	Phone               string `json:"phone"` //1
	Number              string `json:"number"`
	ClientStaticKeypair string `json:"ClientStaticKeypair"` //1  ==
	ClientKey           string `json:"clientKey"`
	Ipub                string `json:"ipub"`      //publicKey 消息公钥  //1
	Ipri                string `json:"ipri"`      //privateKey 消息私钥 //1
	Rid                 string `json:"rid"`       //registrationId   //2
	PushName            string `json:"pushName"`  //2
	Me                  string `json:"me"`        //1
	Mcc                 string `json:"mcc"`       //2
	Mnc                 string `json:"mnc"`       //2
	Routing             string `json:"routing"`   //2
	PhoneId             string `json:"phoneidId"` //2
	Manufacturer        string `json:"manufacturer"`
	Device              string `json:"device"`
	OsBuildNumber       string `json:"obn"`
	OsVersion           string `json:"version"`
	Kv                  string `json:"kv"`
	StaticPriKey        string `json:"-"` //登录私钥
	StaticPubKey        string `json:"-"` //登录公钥

	//以下是附加字段
	ReuseCount    int32       `json:"reuseCount"`
	LoggedOkCount int32       `json:"loggedOkCount"` //登录成功次数
	IsTest        bool        `json:"-"`             //测试
	Logger        *zap.Logger `json:"_"`             //跟踪token
}

func (data *WasTokenBean) FixData() {
	if data.ClientId == "" || strings.Contains(data.ClientId, "0000-") { //00000000-0000-0000-0000-000000000000 无效gid
		data.ClientId = strings.ToLower(guuid.New().String())
	}
	data.Dt = time.Now().Format("2006-01-02 15:04:05")
	if data.ClientKey != "" {
		data.ClientStaticKeypair = data.ClientKey + "=="
	}
	if data.Me != "" {
		data.Phone = data.getPhoneNumber(data.Me)
	} else if data.Number != "" {
		data.Phone = data.Number
	}
}
func (data *WasTokenBean) getPhoneNumber(me string) string {
	b, _ := base64.URLEncoding.DecodeString(me)
	str := string(b)
	reg := regexp.MustCompile(`\d{9,14}`)
	result := reg.FindAllStringSubmatch(str, 1)
	if len(result) > 0 {
		return result[0][0]
	}
	return ""
}
func (data *WasTokenBean) AddLoggedOkCount(count int32) {
	atomic.AddInt32(&data.LoggedOkCount, count)
}
func (data *WasTokenBean) GetLoggedOkCount() int32 {
	return atomic.LoadInt32(&data.LoggedOkCount)
}
func (data *WasTokenBean) AddReuseCount(count int32) {
	atomic.AddInt32(&data.ReuseCount, count)
}
func (data *WasTokenBean) ToString() string {
	ba, _ := json.Marshal(data)
	return string(ba)
}
